import React, {Component} from 'react';
import {connect} from 'dva';
import {Button, Card, Col, Form, Input, message, Modal, Popconfirm, Row, Spin, Table, Tooltip,} from 'antd';
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import {FormattedMessage} from 'umi/locale';
import APP from "@/components/Tool/BaseAPP";

/**
 * 分页参数
 * @Author 彭长雄
 */
let pagingData = {
    _pageSize: 10,
    _current: 1,
    _total: 0,
};

@connect(({sysParamsModel}) => ({
    sysParamsModel,
}))
@Form.create()
class SysParams extends Component {
    state = {
        loading: false,
        pageDataSource: [],
        selectedKeys: [],
        isShowEditModal: false,
        editData: {},
    };

    componentDidMount() {
        //-- 获取报表数据
        this.findPageDataSource();
    }

    /**
     * 查询系统参数数据
     */
    findPageDataSource = e => {
        let that = this, params = {...pagingData};
        if (e) {
            pagingData._current = 1;
            e.preventDefault();
        }
        const {form} = this.props;
        form.validateFieldsAndScroll((err, values) => {
            APP.validNilParams(values);
            params = {...params, ...values};
            requestContinue();
        });

        function requestContinue() {
            const {dispatch} = that.props;
            APP.loading(that);
            dispatch({
                type: "sysParamsModel/list",
                payload: params,
                callback: function (data) {
                    APP.closeLoading(that);
                    if (data.success) {
                        const {list, pagination} = data.datas;
                        pagingData._current = pagination.current;
                        pagingData._pageSize = pagination.pageSize;
                        pagingData._total = pagination.total;
                        that.setState({
                            pageDataSource: list,
                            selectedKeys: []
                        });
                    }
                }
            });
        }
    };

    getDataById = () => {
        const {selectedKeys} = this.state;
        if (selectedKeys.length !== 1) return;
        const that = this,
            {dispatch} = that.props,
            id = selectedKeys[0];
        if (!APP.isValidObj(id)) return;
        APP.loading(that);
        dispatch({
            type: "sysParamsModel/getSysParamsById",
            payload: {id: id},
            callback: function (data) {
                that.setState({
                    loading: false,
                    editData: data.datas,
                    isShowEditModal: true
                });
            }
        });
    };

    enabledControl = (isEnabled) => {
        const {selectedKeys} = this.state;
        if (selectedKeys <= 0) return;
        const that = this, {dispatch} = this.props;
        APP.loading(that);
        dispatch({
            type: "sysParamsModel/enabledControl",
            payload: {
                ids: selectedKeys.join(","),
                isEnabled: isEnabled
            },
            callback: function (data) {
                APP.closeLoading(that);
                if (data.success) {
                    message.success("操作成功");
                    that.findPageDataSource();
                } else {
                    message.error("操作失败！");
                }
            }
        });
    };

    render() {
        const that = this;
        const {
            loading,
            pageDataSource,
            selectedKeys
        } = that.state;
        const {form} = that.props;
        const {getFieldDecorator} = form;
        return (
            <Spin spinning={loading}>
                <PageHeaderWrapper title={<FormattedMessage id="menu.settings.sysParams"/>}>
                    <Card style={{marginBottom: 15}}>
                        <Form layout="inline" onSubmit={this.findPageDataSource}>
                            <Row>
                                <Col span={8}>
                                    <Form.Item label="参数名称">
                                        {getFieldDecorator('name', {})(<Input placeholder="请输入参数名称"
                                                                              allowClear={true}/>)}
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col style={{textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20}}>
                                    <Button type="primary" htmlType="submit" {...APP.buttonsStyle_MR15}>
                                        查找
                                    </Button>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card style={{marginBottom: 15}}>
                        <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                            this.setState({isShowEditModal: true});
                        }}>
                            新增
                        </Button>
                        <Tooltip
                            title={selectedKeys.length === 1 ? '' : '请选中一行数据'}
                        >
                            <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                                this.getDataById();
                            }}>
                                编辑
                            </Button>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Popconfirm
                                title="确定删除选中数据吗？"
                                onConfirm={() => {
                                    this.enabledControl(-1);
                                }}
                                okText="删除"
                                cancelText="取消"
                                disabled={!(selectedKeys.length > 0)}
                            >
                                <Button type="primary" {...APP.buttonsStyle_MR15}>
                                    删除
                                </Button>
                            </Popconfirm>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Popconfirm
                                title="确定启用选中数据吗？"
                                onConfirm={() => {
                                    this.enabledControl(1);
                                }}
                                okText="启用"
                                cancelText="取消"
                                disabled={!(selectedKeys.length > 0)}
                            >
                                <Button type="primary" {...APP.buttonsStyle_MR15}>
                                    启用
                                </Button>
                            </Popconfirm>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Popconfirm
                                title="确定不启用选中数据吗？"
                                onConfirm={() => {
                                    this.enabledControl(0);
                                }}
                                okText="不启用"
                                cancelText="取消"
                                disabled={!(selectedKeys.length > 0)}
                            >
                                <Button type="primary" {...APP.buttonsStyle_MR15}>
                                    不启用
                                </Button>
                            </Popconfirm>
                        </Tooltip>
                    </Card>
                    <Card>
                        <Table
                            bordered
                            rowKey={data => `${data.id}`}
                            rowSelection={APP.tableRowSelection(function (selectedRowKeys, selectedRows) {
                                that.setState({selectedKeys: selectedRowKeys});
                            }, selectedKeys)}
                            columns={this.columns}
                            dataSource={pageDataSource}
                            pagination={{
                                pageSize: pagingData._pageSize,
                                current: pagingData._current,
                                total: pagingData._total,
                                onChange: (page, pageSize) => {
                                    pagingData._current = page;
                                    this.findPageDataSource();
                                },
                                showTotal: total => `共 ${total} 条数据`,
                            }}
                        />
                    </Card>
                    <EditForm parent={this}/>
                </PageHeaderWrapper>
            </Spin>
        );
    }

    /**
     * 表格列
     */
    columns = [{
        title: '可用标识',
        dataIndex: 'isenabled',
        key: 'isenabled',
    }, {
        title: '参数名称',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '参数值',
        dataIndex: 'val',
        key: 'val',
    }, {
        title: '业务引用键',
        dataIndex: 'recode',
        key: 'recode',
    }, {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
    }];
}

const EditForm = Form.create()(props => {
    let {parent, form} = props;
    const {dispatch} = parent.props;
    const {loading, isShowEditModal, editData} = parent.state;
    const formItemLayout = {
        style: {
            margin: '0px',
        },
    };
    const {getFieldDecorator} = form;

    //-- 显示/隐藏 数据编辑窗口
    function handlerEditModal() {
        form.resetFields();
        let {isShowEditModal, editData} = parent.state;
        isShowEditModal = !isShowEditModal;
        editData = {};
        parent.setState({isShowEditModal, editData});
    }

    const colFloatRight = {
        style: {
            float: 'right'
        },
    };

    function submit() {
        form.validateFields((err, values) => {
            if (err) return;
            APP.validNilParams(values);
            request(values);
        });

        function request(params) {
            APP.loading(parent);
            dispatch({
                type: "sysParamsModel/saveSysParams",
                payload: params,
                callback: function (data) {
                    APP.closeLoading(parent);
                    if (data.success) {
                        message.success("保存成功！");
                        parent.findPageDataSource();
                        handlerEditModal();
                    } else {
                        message.error(data.msg);
                    }
                }
            });
        }
    }

    return (
        <Modal
            title={<FormattedMessage id="menu.settings.sysParams.editSysParams"/>}
            visible={isShowEditModal}
            onOk={() => submit()}
            onCancel={() => handlerEditModal()}
            okText="保存"
            cancelText='返回'
            confirmLoading={loading}
        >
            <Form layout="vertical">
                {getFieldDecorator('id', {initialValue: editData.id})(<Input hidden={true}/>)}
                <Row>
                    <Col span={11}>
                        <Form.Item label="引用业务值" {...formItemLayout}>
                            {getFieldDecorator('recode', {
                                initialValue: editData.recode,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入引用业务值！',
                                    },
                                ],
                            })(<Input placeholder="请输入引用业务值" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                    <Col span={11} {...colFloatRight}>
                        <Form.Item label="参数名称" {...formItemLayout}>
                            {getFieldDecorator('name', {
                                initialValue: editData.name,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入参数名称！',
                                    },
                                ],
                            })(<Input placeholder="请输入参数名称" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={11}>
                        <Form.Item label="参数值" {...formItemLayout}>
                            {getFieldDecorator('val', {
                                initialValue: editData.val,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入参数值！',
                                    },
                                ],
                            })(<Input placeholder="请输入参数值" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Form.Item label="备注" {...formItemLayout}>
                        {
                            getFieldDecorator('remark', {
                                initialValue: editData.remark,
                            })(
                                <Input.TextArea
                                    placeholder="请输入备注"
                                    className="custom"
                                    style={{
                                        height: 150,
                                        width: "100%",
                                        resize: 'none'
                                    }}
                                />
                            )
                        }
                    </Form.Item>
                </Row>
            </Form>
        </Modal>);
});

export default SysParams;
